package com.jb.repair.fragment;

import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jb.repair.F1Application;
import com.jb.repair.R;
import com.jb.repair.acticity.MainActivity;
import com.jb.repair.acticity.TaskDetailActivity;
import com.jb.repair.adapter.RegularTaskAdapter;
import com.jb.repair.common.AppConfig;
import com.jb.repair.common.Constants;
import com.jb.repair.common.DialogOnResultCallback;
import com.jb.repair.common.DialogUtil;
import com.jb.repair.dao.LocalDbDao;
import com.jb.repair.model.RegularTaskModel;
import com.jb.repair.model.RegularWorkListJson;
import com.jb.repair.model.RegularWorkModel;
import com.jb.repair.model.ResponseModel;
import com.jb.repair.model.TaskTableModel;
import com.jb.repair.model.UpdateCheck4Json;
import com.jb.repair.model.User4Json;
import com.jb.repair.net.HttpClient;
import com.jb.repair.net.HttpCookies;
import com.jb.repair.util.MD5Util;
import com.jb.repair.util.MessageUtil;
import com.jb.repair.view.ItemTitleView;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class RegularFragment extends Fragment implements MainActivity.OnMainListener, DialogOnResultCallback, View.OnClickListener {

    private static final String TAG = "RegularFragment";

    /* view 类变量 */
    private ItemTitleView itemTitleView;
    private RelativeLayout rlTaskListHeader;//任务列表listview头部
    private ListView lvTaskList;//任务列表
    private RelativeLayout rlTaskListFoot;//任务列表Listview尾部
    private Spinner spiProfess, spiStatus;
    private TextView tvTaskNum;//任务数目
    private ImageView ivFirst, ivPrev, ivNext, ivLast, ivGo;//导航按钮
    private EditText etCurrentPageIndex;//当前页
    private TextView tvPageNum;//总页数

    /* 数据相关 */
    private RegularTaskAdapter regularTaskAdapter = null;
    private List<RegularWorkModel> regularWorkList = new ArrayList<RegularWorkModel>();
    private int taskNum = 0;//任务总数
    private int index = 1;//当前页号
    private int offset = 0;//偏移量
    private int pagesNum = 1;//总页数
    SharedPreferences sp;
    private Gson gson = new Gson();
    private String timestamp;//上次获取定期工作的时间戳
    LocalDbDao localDbDao = null;
    private static final int REGULAR_WORK_NUM = 10;//每页显示任务数目
    private static final int LIMIT_COUNT_OF_EACH_PAGE = 10;//每页显示的条数
    private int listItemIndex = -1;
    private int operationType = -1;
    RegularWorkModel model = null;
    private boolean search = false;
    private Map<String, String> map = null;

    private Context context;

    public RegularFragment() {}

    public static RegularFragment newInstance() {
        RegularFragment fragment = new RegularFragment();
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        Log.i(TAG, "onCreate");
        super.onCreate(savedInstanceState);
        context = getActivity();
        sp = context.getSharedPreferences(Constants.SP_NAME, context.MODE_PRIVATE);
        //初始化业务数据
        initVariables();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Log.i(TAG, "onCreateView");

        //初始化视图
        View view = initViews(inflater);


        return view;
    }

    @Override
    public void onResume() {
        super.onResume();

        //初始化数据
        initData();
        //添加监听
        initListeners();
    }

    /**
     * 初始化业务数据
     */
    private void initVariables() {
        //初始化spinner

        //初始化最近获取数据的时间戳
        //timestamp = sp.getString(Constants.LAST_GET_REGULAR_WORK_TIME, "1970-01-01 00:00:00");
        localDbDao = LocalDbDao.getInstance(context);
    }

    private View initViews(LayoutInflater inflater) {
        View view = inflater.inflate(R.layout.fragment_regular, null);
        itemTitleView = (ItemTitleView) view.findViewById(R.id.title_task_list);
        lvTaskList = (ListView)view.findViewById(R.id.lv_task_list);
        //添加头部
        rlTaskListHeader = (RelativeLayout) inflater.inflate(R.layout.layout_task_list_header, null);
        lvTaskList.addHeaderView(rlTaskListHeader);
        //添加尾部
        rlTaskListFoot = (RelativeLayout) inflater.inflate(R.layout.layout_task_list_foot, null);
        tvTaskNum = (TextView) rlTaskListFoot.findViewById(R.id.tv_task_num);
        ivFirst = (ImageView) rlTaskListFoot.findViewById(R.id.iv_go_to_first);
        ivPrev = (ImageView) rlTaskListFoot.findViewById(R.id.iv_go_to_prev);
        ivNext = (ImageView) rlTaskListFoot.findViewById(R.id.iv_go_to_next);
        ivLast = (ImageView) rlTaskListFoot.findViewById(R.id.iv_go_to_last);
        ivGo = (ImageView) rlTaskListFoot.findViewById(R.id.iv_go_to_specied);
        tvPageNum = (TextView) rlTaskListFoot.findViewById(R.id.tv_page_num);
        etCurrentPageIndex = (EditText) rlTaskListFoot.findViewById(R.id.et_index);
//        lvTaskList.addFooterView(rlTaskListFoot);//去掉分页
        return view;
    }

    private void initData() {
        if (search)
            showSearchResult(map);
        else
            showRegularWork();
    }

    private void initListeners() {

        //列表项点击监听
        lvTaskList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                RegularWorkModel model = regularWorkList.get(i - 1);
                Intent intent = new Intent(context, TaskDetailActivity.class);
                intent.putExtra("task_detail", model);
                startActivity(intent);
            }
        });
        //长按监听
        lvTaskList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                DialogUtil.selectOperationDialog(context, i - 1, RegularFragment.this);
                return true;
            }
        });

        //翻页监听
        ivFirst.setOnClickListener(this);
        ivPrev.setOnClickListener(this);
        ivNext.setOnClickListener(this);
        ivLast.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_go_to_first:
                if (offset > 0)
                    offset = 0;
                break;
            case R.id.iv_go_to_prev:
                break;
            case R.id.iv_go_to_next:
                break;
            case R.id.iv_go_to_last:
                break;
        }
    }

    @Override
    public void onAttach(Activity activity) {
        Log.i(TAG, "onAttach");
        super.onAttach(activity);
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }


    /**
     * 同步定期工作（先下载，后上传）
     */
    private void syncRegularWork() {
        //首先下载最新的定期工作
        MessageUtil.showProgressDialog(context, "正在请求定期工作");
        new getRegularWorkTask().execute();

    }


    private class getRegularWorkTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {

            String url = Constants.GET_REGULAR_WORK_URL.contains("http") ? Constants.GET_REGULAR_WORK_URL : AppConfig.BASE_URL + Constants.GET_REGULAR_WORK_URL;
            Log.i(TAG, "请求定期工作URL：" + url);
            Map<String, String> map = new HashMap<>();
            map.put("persId", F1Application.getUserId() == null ? Constants.FAKE_LOGIN_ID : F1Application.getUserId());
            Log.i(TAG, "参数为：" + map.toString());
            String result = new HttpClient(context).doPost(url, map);
            Log.i(TAG, "请求定期工作返回結果：" + result);
            return result;
        }

        @Override
        protected void onPostExecute(String s) {
            MessageUtil.dismissProgressDialog();
            super.onPostExecute(s);
            JSONObject resultJson = null;
            RegularWorkListJson regularWorkListJson = null;
            try {
                resultJson = new JSONObject(s);
                Log.i(TAG, "解析成功");
            } catch (JSONException e) {
                e.printStackTrace();
                new LoginTask().execute(F1Application.getUserId(), MD5Util.parse("000"), "0");//0-表示同步定期工作

            }
            try {
                if (resultJson != null) {
                    if (resultJson.has("success") && resultJson.getInt("success") == 0) {
                        //返回成功
                        if (resultJson.has("taskList")) {
                            Log.i(TAG, "开始解析taskList...");
                            regularWorkList = gson.fromJson(resultJson.getJSONArray("taskList").toString(), new TypeToken<List<RegularWorkModel>>() {
                            }.getType());

                            Log.i(TAG, "taskList解析成功" + regularWorkList.toString());
                            MessageUtil.showToast(context, resultJson.has("msg") ? resultJson.getString("msg") : "下载定期工作成功");

                        } else {
                            MessageUtil.showToast(context, "无任务");
                        }
                    } else if (resultJson.has("success") && resultJson.getInt("success") == 1) {
                        MessageUtil.showToast(context, resultJson.has("msg") ? resultJson.getString("msg") : "任务解析失败");
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
                Log.e(TAG, "解析json数据时发生异常");
                regularWorkList = null;
            }
            if (regularWorkList != null) {
                //存储到数据库中
                saveRegularWorkToDb(regularWorkList);

                //显示到界面中
                showRegularWork();
//                MessageUtil.showToast(context, "下载定期工作成功");
            }


        }
    }

    /**
     * 模拟登录用以获取cookie
     */
    private class LoginTask extends AsyncTask<String, Void, String> {
        private String type = "";

        @Override
        protected String doInBackground(String... params) {
            type = params[2];
            String url = Constants.LOGIN_URL_FRO_REGULAR.contains("http") ? Constants.LOGIN_URL_FRO_REGULAR : AppConfig.BASE_URL + Constants.LOGIN_URL_FRO_REGULAR;
            Log.i(TAG, "登陆url：" + url);
            String result = "";
            Map<String, String> map = new HashMap<>();
            map.put("username", params[0]);
            map.put("password", params[1]);
            map.put("pageStyle", "");
            map.put("logined", params[0]);
            map.put("agent", "0");
            result = new HttpClient(context).doPost(url, map);
            Log.i(TAG, "登陆返回结果：" + result);
            return result;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            Gson gson = new Gson();
            try {
                User4Json uj = gson.fromJson(s, new TypeToken<User4Json>() {
                }.getType());
                if (uj.successful.equals("true")) {
                    MessageUtil.showToast(context, "验证成功");
                    F1Application.setUserName(uj.resultValue.persName);
                    F1Application.setUserId(uj.resultValue.persGuid);
                    MessageUtil.showProgressDialog(context, "正在请求定期工作");
                    if (type.equals("0"))//同步定期工作
                        new getRegularWorkTask().execute();
                    else if (type.equals("1"))//上传定期工作结果（延期、取消、完工）
                        new UploadRegularWorkTask().execute(operationType + "", listItemIndex + "");
                } else {
                    MessageUtil.showToast(context, uj.resultHint);
                    HttpCookies.setSessionId(null);
                }
            } catch (Exception e) {
                MessageUtil.showToast(context, "验证失败");
            }


        }
    }

    /**
     * 上传定期工作
     * 参数1 —— 类型 0-延期 1-取消 2-完工
     * 参数2 —— 定期工作model序号
     */
    private class UploadRegularWorkTask extends AsyncTask<String, Void, String> {

        private String type = "";

        @Override
        protected String doInBackground(String... params) {

            type = params[0];
            RegularWorkModel model = regularWorkList.get(Integer.parseInt(params[1]));

            String url = "";
            Map<String, String> map = new HashMap<>();

            if (type.equals("0")) {
                //延期
                url = Constants.TASK_DELAY_URL.contains("http") ? Constants.TASK_DELAY_URL : AppConfig.BASE_URL + Constants.TASK_DELAY_URL;
                map.put("guid", model.GUID);
                map.put("yqsj", model.DELAY_TIME);
                map.put("yqyy", model.DELAY_RESULT);
                map.put("flag", "update");
            } else if (type.equals("1")) {
                //取消
                url = Constants.TASK_CANCEL_URL.contains("http") ? Constants.TASK_CANCEL_URL : AppConfig.BASE_URL + Constants.TASK_CANCEL_URL;
                map.put("guid", model.GUID);
                map.put("qxyy", model.cancel_result);
                map.put("flag", "update");
            } else if (type.equals("2")) {
                //完工
                url = Constants.TASK_COMPLETE_URL.contains("http") ? Constants.TASK_COMPLETE_URL : AppConfig.BASE_URL + Constants.TASK_COMPLETE_URL;
                map.put("guid", model.GUID);
                map.put("zxrid", model.CT_PERSON_ID);//todo 不确定CT_PERSON_ID是不是执行人ID
                map.put("wcsj", model.FINISHED_TIME);
                map.put("wcqk", model.completion);
                map.put("flag", "update");
                map.put("djrid", F1Application.getUserId() == null ? Constants.FAKE_LOGIN_ID : F1Application.getUserId());
            }

            Log.i(TAG, "上传定期工作状态至服务器 URL：" + url);
            Log.i(TAG, "上传定期工作状态至服务器 参数为：" + map.toString());
            String result = new HttpClient(context).doPost(url, map);
            Log.i(TAG, "上传定期工作返回結果：" + result);
            return result;
        }

        @Override
        protected void onPostExecute(String s) {
            MessageUtil.dismissProgressDialog();
            super.onPostExecute(s);
            try {
                JSONObject jsonObject = new JSONObject(s);
                if (type.equals("0")) {
                    //延期
                    if (jsonObject.has("success") && jsonObject.getString("success").contains("成功")) {
                        MessageUtil.showToast(context, "延期提交成功");
                        //保存到数据库中(定期工作表中)
                        model.TASK_STATUS = "0700205";
                        localDbDao.updateRegularWork(1, model);
                        //刷新当前页面
                        regularWorkList.get(listItemIndex).TASK_STATUS = "0700205";
                        regularTaskAdapter.notifyDataSetChanged();

                    } else if (jsonObject.has("success") && jsonObject.getString("success").contains("失败")) {
                        MessageUtil.showToast(context, jsonObject.getString("success"));
                    } else {
                        MessageUtil.showToast(context, "延期提交失败");
                    }
                } else if (type.equals("1")) {
                    //取消
                    if (jsonObject.has("success") && jsonObject.getString("success").contains("成功")) {
                        MessageUtil.showToast(context, "取消提交成功");
                        //保存到数据库中
                        model.TASK_STATUS = "0700206";
                        localDbDao.updateRegularWork(2, model);
                        //刷新当前页面
                        regularWorkList.get(listItemIndex).TASK_STATUS = "0700206";
                        regularTaskAdapter.notifyDataSetChanged();
                    } else if (jsonObject.has("success")) {
                        MessageUtil.showToast(context, jsonObject.getString("success"));
                    } else {
                        MessageUtil.showToast(context, "取消提交失败");
                    }
                } else if (type.equals("2")) {
                    //完工
                    Log.i(TAG, "完工返回");
                    MessageUtil.showToast(context, "已提交完工情况");

                    //比较登记时间和应完成时间，来决定当前定期工作的状态（已完成 or 超期已完成）
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                    try {
                        long finishTime = sdf.parse(model.FINISHED_TIME).getTime();
                        Log.i(TAG, "finishTIme = " + finishTime);
                        long shouldFinishTime = sdf.parse(model.SHOULD_FINISH_TIME.length() == 10 ? model.SHOULD_FINISH_TIME + " 23:59" : model.SHOULD_FINISH_TIME).getTime();
                        Log.i(TAG, "shouldFinishTime = " + shouldFinishTime);
                        if (finishTime < shouldFinishTime) {
                            Log.i(TAG, "状态为： 已完成");
                            model.TASK_STATUS = "0700202";//已完成
                        } else {
                            Log.i(TAG, "状态为： 超期已完成");
                            model.TASK_STATUS = "0700204";//超期已完成
                        }
                        //保存到数据库中
                        localDbDao.updateRegularWork(3, model);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    //刷新当前页面
                    regularTaskAdapter.notifyDataSetChanged();
                }
            } catch (JSONException e) {
                e.printStackTrace();
                Log.e(TAG, "JSON格式解析错误");
                if (s.contains("601")) {
                    //登录授权
                    new LoginTask().execute(Constants.LOGIN_NAME_FRO_REGULAR, MD5Util.parse("000"), "1");//1-重新调用UploadRegularWorkTask
                } else if (Boolean.parseBoolean(s)) {

                    MessageUtil.showToast(context, "已提交完工情况");


                    //比较登记时间和应完成时间，来决定当前定期工作的状态（已完成 or 超期已完成）
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm");
                    try {
                        long finishTime = sdf.parse(model.FINISHED_TIME).getTime();
                        Log.i(TAG, "finishTIme = " + finishTime);
                        long shouldFinishTime = sdf.parse(model.SHOULD_FINISH_TIME.length() == 10 ? model.SHOULD_FINISH_TIME + " 23:59" : model.SHOULD_FINISH_TIME).getTime();
                        Log.i(TAG, "shouldFinishTime = " + shouldFinishTime);
                        if (finishTime < shouldFinishTime) {
                            Log.i(TAG, "状态为： 已完成");
                            model.TASK_STATUS = "0700202";//已完成
                        } else {
                            Log.i(TAG, "状态为： 超期已完成");
                            model.TASK_STATUS = "0700204";//超期已完成
                        }
                        //保存到数据库中
                        localDbDao.updateRegularWork(3, model);
                    } catch (ParseException e2) {
                        e2.printStackTrace();
                    }
                    //刷新当前页面
                    regularTaskAdapter.notifyDataSetChanged();
                }
            } catch (Exception e1) {
                e1.printStackTrace();
                MessageUtil.showToast(context, "提交失败，请稍后重试");
            }

        }
    }

    /**
     * 保存到数据库中
     *
     * @param regularWorkModelList
     */
    private void saveRegularWorkToDb(List<RegularWorkModel> regularWorkModelList) {
        if (localDbDao != null)
            localDbDao.insertIntoCtTask(regularWorkModelList);
        else
            Log.e(TAG, "localDbDao = null");
    }

    /**
     * 将定期工作显示到界面中
     */
    private void showRegularWork() {
        if (localDbDao != null) {
            //初始化列表数据
            regularWorkList = localDbDao.getLastRegularWorks(F1Application.getUserId(), REGULAR_WORK_NUM, offset);
            regularTaskAdapter = new RegularTaskAdapter(context, regularWorkList);
            lvTaskList.setAdapter(regularTaskAdapter);
            regularTaskAdapter.notifyDataSetChanged();
            //初始化底部数据
            taskNum = regularWorkList.size();
//            offset += taskNum;
            tvTaskNum.setText(taskNum + "");
            if (taskNum % LIMIT_COUNT_OF_EACH_PAGE == 0)
                pagesNum = taskNum / LIMIT_COUNT_OF_EACH_PAGE;
            else
                pagesNum = taskNum / LIMIT_COUNT_OF_EACH_PAGE + 1;
            etCurrentPageIndex.setText("1");
            tvPageNum.setText(pagesNum + "");
        }
        itemTitleView.setTvLeftText("任务列表");
        itemTitleView.setTvRightText("同步数据");
        //同步数据监听
        itemTitleView.setOnClickListener(new ItemTitleView.OnItemTitleViewClickListener() {
            @Override
            public void onRightTextClick(View view) {
                super.onRightTextClick(view);
                syncRegularWork();
            }

            @Override
            public void onRightBtnClick(View view) {
                super.onRightBtnClick(view);
            }
        });

    }

    @Override
    public void onMainAction(Map params) {
        Log.i(TAG, "收到参数为：" + params.toString());
        search = true;
        map = params;
        showSearchResult(params);
    }

    private void showSearchResult(Map params) {
        if (localDbDao != null) {
            //初始化列表数据
            regularWorkList = localDbDao.getSearchResult(F1Application.getUserId(), REGULAR_WORK_NUM, params);
//            if(regularTaskAdapter == null){
            regularTaskAdapter = new RegularTaskAdapter(context, regularWorkList);
            lvTaskList.setAdapter(regularTaskAdapter);
//            }
            regularTaskAdapter.notifyDataSetChanged();
            //初始化底部数据
            taskNum = regularWorkList.size();
            tvTaskNum.setText(taskNum + "");
            if (taskNum % LIMIT_COUNT_OF_EACH_PAGE == 0)
                pagesNum = taskNum / LIMIT_COUNT_OF_EACH_PAGE;
            else
                pagesNum = taskNum / LIMIT_COUNT_OF_EACH_PAGE + 1;
            etCurrentPageIndex.setText("1");
            tvPageNum.setText(pagesNum + "");
        }
        //更改标题
        itemTitleView.setTvLeftText("搜索结果");
        itemTitleView.setTvRightText("返回任务列表");
        //同步数据监听
        itemTitleView.setOnClickListener(new ItemTitleView.OnItemTitleViewClickListener() {
            @Override
            public void onRightTextClick(View view) {
                super.onRightTextClick(view);
                search = false;
                showRegularWork();
            }

            @Override
            public void onRightBtnClick(View view) {
                super.onRightBtnClick(view);
            }
        });
    }

    /**
     * @param type   0-从操作页面返回 1-从延期页面返回 2-从完工页面返回 3-从取消页面返回
     * @param bundle
     */
    @Override
    public void onResult(int type, Bundle bundle) {
        switch (type) {
            case 0:
                //从操作页面返回
                Log.i(TAG, "从操作页面返回");
                goOperation(bundle);
                break;
            case 1:
                //从延期页面返回
                delayOperation(bundle);
                break;
            case 2:
                //从取消页面返回
                cancelOperation(bundle);
                break;
            case 3:
                //从完工页面返回
                completeOperation(bundle);
                break;
        }

    }

    private void goOperation(Bundle bundle) {
        int itemId = bundle.getInt("itemId");
        listItemIndex = itemId;
        RegularWorkModel model = regularWorkList.get(itemId);
        int select = bundle.getInt("select");
        Log.i(TAG, "select = " + select);
        switch (select) {
            case 0:
                //查看详情
                //跳转到任务详情页面
                Intent intent = new Intent(context, TaskDetailActivity.class);
                intent.putExtra("task_detail", model);
                startActivity(intent);
                break;
            case 1:
                //延期
                //弹出延期页面
                if (model.TASK_STATUS.equals("0700206")) {
//                    DialogUtil.popDelayPage(context, itemId, RegularFragment.this, model.DELAY_RESULT);
                    MessageUtil.showToastDialog(context, "提示", "该任务已取消");

                }
                else if (model.TASK_STATUS.equals("0700204") || model.TASK_STATUS.equals("0700202"))
                    MessageUtil.showToastDialog(context, "提示", "该任务已完成");
                else
                    DialogUtil.popDelayPage(context, itemId, RegularFragment.this, model.DELAY_RESULT);

                break;
            case 2:
                //取消
                //弹出取消页面
                DialogUtil.popCancelPage(context, itemId, RegularFragment.this, model.cancel_result);
                break;
            case 3:
                //完工
                if (allTaskTableDone(model.GUID) && !model.TASK_STATUS.equals("0700206")) {//所有小任务都完成并且没有取消
                    //弹出完工页面
                    DialogUtil.popCompletePage(context, itemId, RegularFragment.this, model.completion);
                } else if (model.TASK_STATUS.equals("0700206")) {
                    //已取消
                    MessageUtil.showToastDialog(context, "提示", "该任务已取消");
                } else {
                    MessageUtil.showToastDialog(context, "提示", "还有未上传的任务表");
                }
                break;
        }
    }

    private void delayOperation(Bundle bundle) {
        int itemId = bundle.getInt("itemId");
        listItemIndex = itemId;
        int select = bundle.getInt("select");
        if (select == 1) {
            //1代表确认
            String date = bundle.getString("date");
            Log.i(TAG, "delay date = " + date);
            String reason = bundle.getString("reason");
            Log.i(TAG, "reason = " + reason);
            model = regularWorkList.get(itemId);
            model.DELAY_TIME = date;
            model.DELAY_RESULT = reason;
            model.update_time = new SimpleDateFormat("yyyy-MM-dd hh:mm").format(new Date()).toString();
            Log.i(TAG, "update time = " + model.update_time);

            //发送到服务器
            MessageUtil.showProgressDialog(context, "正在提交");
            operationType = 0;
            new UploadRegularWorkTask().execute(operationType + "", itemId + "");//0-延期
        }
    }

    private void cancelOperation(Bundle bundle) {
        int itemId = bundle.getInt("itemId");
        listItemIndex = itemId;
        int select = bundle.getInt("select");
        if (select == 1) {
            //1代表确认
            String date = bundle.getString("date");
            Log.i(TAG, "cancel date = " + date);
            String reason = bundle.getString("reason");

            model = regularWorkList.get(itemId);
            model.update_time = date;
            model.cancel_result = reason;

            Log.i(TAG, "cancel_result = " + model.cancel_result);

            //发送到服务器
            MessageUtil.showProgressDialog(context, "正在提交");
            operationType = 1;
            new UploadRegularWorkTask().execute(operationType + "", itemId + "");//1-取消
        }
    }

    private void completeOperation(Bundle bundle) {
        int itemId = bundle.getInt("itemId");
        listItemIndex = itemId;
        int select = bundle.getInt("select");
        if (select == 1) {
            //1代表确认
            model = regularWorkList.get(itemId);
            model.completion = bundle.getString("intro");
            String date = bundle.getString("date");
            model.FINISHED_TIME = date;
            model.update_time = date;


            //发送到服务器
            MessageUtil.showProgressDialog(context, "正在提交");
            operationType = 2;
            new UploadRegularWorkTask().execute(operationType + "", itemId + "");//2-完工
        }
    }

    /**
     * 检查该定期工作下的任务表是否都已上传(提交)
     *
     * @param taskId
     */
    private boolean allTaskTableDone(String taskId) {
        List<TaskTableModel> list = localDbDao.getTaskTableListById(taskId);
        if (list != null) {
            if (list.size() > 0) {
                for (TaskTableModel model : list) {
                    if (!model.STATUS.equals("2"))
                        return false;
                }
                return true;
            } else {
                MessageUtil.showToast(context, "该定期工作任务表未下载");
                return false;
            }
        }
        return false;
    }
}
